package cn.common.component.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Author by wangxudongx
 */
public class ComponentUtils {


    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ComponentUtils.class);


    /**
     * basic auth
     * 2019年11月15日
     * @param uri
     * @param username
     * @param password
     * @return
     */
    public static JSONObject sendHttpRequestByGet(String uri, String username, String password) {
        JSONObject result = new JSONObject();
        SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        try {
            ClientHttpRequest clientHttpRequest = simpleClientHttpRequestFactory.createRequest(new URI(uri), HttpMethod.GET);



            String userMsg = username + ":" + password;
            String base64UserMsg =     org.apache.tomcat.util.codec.binary.Base64.encodeBase64String(userMsg.getBytes());
            base64UserMsg = "Basic " +base64UserMsg;
            clientHttpRequest.getHeaders().set("Authorization",base64UserMsg);

            ClientHttpResponse clientHttpResponse = clientHttpRequest.execute();

            log.info( "Status《" + clientHttpResponse.getStatusText()+"：" + clientHttpResponse.getStatusCode() + "》");

            clientHttpResponse.getHeaders().keySet().forEach(i->{
                clientHttpResponse.getHeaders().get(i).forEach(ii->{
                    log.info( i+"："+ ii );

                });
            });

            try(InputStreamReader inputStreamReader = new InputStreamReader(clientHttpResponse.getBody())){
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                StringBuffer stringBuffer = new StringBuffer();
                while (bufferedReader.ready()) {
                    stringBuffer.append(bufferedReader.readLine());
                }
                result = JSON.parseObject(stringBuffer.toString());
            }
        } catch (URISyntaxException use) {
            log.error(use.getLocalizedMessage());
        } catch (IOException e) {
            log.error(e.getLocalizedMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 携带Basic Auth 发送Get请求
     * @param url
     * @param userName
     * @param password
     * @return
     */
    public static String sendGetWithBasicAuth(String url , String userName , String password){

        String userMsg = userName + ":" + password;
        String base64UserMsg =     Base64.encodeBase64String(userMsg.getBytes());

        base64UserMsg = "Basic " +base64UserMsg;

        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Authorization",base64UserMsg);

            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {

        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return result;
    }


    /**
     * 生成 1 - x （包括1、x）随机数
     * @param x
     * @return
     */

    public static int randomWithNotZero(int x) {
        int y = 0;
        Random random = new Random();
        y = random.nextInt(x + 1);
        if (y == 0) {
            return randomWithNotZero(x + 1);
        } else {
            return y;
        }
    }

    public static boolean isChineseChar(char c) {
        return String.valueOf(c).matches("[\u4e00-\u9fa5]");
    }

    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
        return days;
    }
}
